<?php
/*
 * @Author: 哲学家乔布斯 <wuyangii@qq.com>
 * @Date: 2022-10-20 21:41:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-07 22:37:15
 * @Descripttion: 商品管理
 */
namespace app\agent\controller\system;
use think\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet; 
use PhpOffice\PhpSpreadsheet\IOFactory; 
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
class Goods extends \app\agent\controller\Common
{
    public function index(){
    
        return view();
    }

    public function list(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
       
        $query = (new \app\common\model\AgentGoodsSku())
                ->alias('agent_goods_sku')
                ->join("{$this->tdb}goods goods","goods.id = agent_goods_sku.goods_id")
                ->field([
                    'agent_goods_sku.id',
                    'agent_goods_sku.stock',
                    'goods.cate_id','goods.title',
                    'agent_goods_sku.sort','agent_goods_sku.is_display',
                    'agent_goods_sku.is_recommend',
                    'agent_goods_sku.money',
                    'agent_goods_sku.money_primary',
                    'agent_goods_sku.money_cost'
                    ])
                ->where(['agent_goods_sku.is_del' => 0,'agent_goods_sku.agent_id' => $this->userInfo['id'],'goods.is_del' => 0]);

        isset($search['goods_title']) && $search['goods_title'] != "" ? $query->where("title like '%{$search['goods_title']}%'") : '';
        $query->order("agent_goods_sku.id desc");
        $where = [];
        if(!empty($search['bus_id'])){
            $where['bus_id'] = $search['bus_id'];
        }
        $list = $query->limit($page, $limit)->where($where)->append(['cate_title'])->select();
        $count = $query->count();
        return self::successResult('',$list,$count);
    }

    
    public function edit(){
     
        if (request()->isPost()) {
            $info = request()->param('info');
            $id = request()->param('id');
            $validate = new \app\common\validate\AgentGoodsSku();
            $result = $validate->scene("add")->check($info);
            if ($result === false) {
                return self::errorResult($validate->getError());
            }
 
            Db::startTrans();
            try{
                $message = "订单创建失败,请重试";
                $process = true;
                $goods = (new \app\common\model\GoodsSku())->where(['id' => $id])->find();
                // $info['end_time'] =  (!empty($info['end_time'])) ? strtotime($info['end_time']) : 0;
                $row = (new \app\common\model\AgentGoodsSku())->where(['id' => $id])->update($info);
                if(!$row){
                    $message = "添加商品失败";
                    $process = false;
                }
               
                if ($process !== false) {
                    Db::commit(); // 提交事务
                } else {
                    Db::rollback(); // 回滚事务
                }

            } catch (\Exception $e) {
                $process = false;
                $message = $e->getMessage();
                Db::rollback(); // 回滚事务
            }
            if ($process !== false) {
                return self::successResult("修成功");
            } else {
                return self::errorResult($message);
            }
           
       
        } else {
            $id = request()->param('id');
            $cate = (new \app\common\model\GoodsCate())->lists();
            $this->assign("cate",$cate);
            $info = (new \app\common\model\AgentGoodsSku())
                            ->alias('agent_goods_sku')
                            ->join("{$this->tdb}goods goods","goods.id = agent_goods_sku.goods_id")
                            ->join("{$this->tdb}goods_sku goods_sku","goods_sku.id = agent_goods_sku.goods_sku_id")
                            ->field([
                                'agent_goods_sku.*',
                                'goods.cate_id',
                                'goods.title as goods_title',
                                'goods_sku.sku_title as goods_sku_title',
                                ])
                            ->where([
                                'agent_goods_sku.is_del' => 0,
                                'agent_goods_sku.agent_id' => $this->userInfo['id'],
                                'agent_goods_sku.id' => $id
                                ])->append(['cate_title'])->find();
            $this->assign("info",$info);
            return view();
        }

    }
    
   public function goods(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
    
        $query = (new \app\common\model\Goods())->where(['is_del' => 0]);

        isset($search['goods_title']) && $search['goods_title'] != "" ? $query->where("title like '%{$search['goods_title']}%'") : '';
        $query->order("id desc");
        $where = [];
        if(!empty($search['bus_id'])){
            $where['bus_id'] = $search['bus_id'];
        }
        $list = $query->limit($page, $limit)->where($where)->append(['cate_title'])->select();
        $count = $query->count();
        return self::successResult('',$list,$count);
    }
        
   public function goods_sku(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
        $goods_id = (new \app\common\model\AgentGoodsSku())->where(['agent_id' => $this->userInfo['id']])->column('goods_sku_id');
        $query = (new \app\common\model\GoodsSku())
                ->alias("goods_sku")
                ->join("{$this->tdb}goods goods","goods.id = goods_sku.goods_id")
                ->field([
                    'goods_sku.id',
                    'goods_sku.money',
                    'goods_sku.sku_title',
                    'goods.img',
                    'goods.title',
                    'goods.introduce',
                    'goods.cate_id',
                    'goods_sku.stock',
                    ])
                ->where(['is_del' => 0])->where('goods_sku.stock > 0')->where('goods_sku.money > 0')->whereNotIn('goods_sku.id',$goods_id);
        !empty($search['title']) ? $query->where("goods.title like '%{$search['title']}%'") : '';
        !empty($search['cate_id']) ? $query->where("goods.cate_id like '%{$search['cate_id']}%'") : '';
        $query->order("goods_sku.id desc");
        $where = [];
        if(!empty($search['bus_id'])){
            $where['bus_id'] = $search['bus_id'];
        }
        $list = $query->limit($page, $limit)->where($where)
                ->append(['cate_title'])
                ->select();
     
        $count = $query->count();
        return self::successResult('',$list,$count);
}

   public function delete(){
        $id = request()->param('id');
        if (empty($id)) $this->error("请选择要删除的数据");
        $table = new \app\common\model\Goods();
        if (is_array($id)) {
            $id = implode(",", $id);
            $row = $table->whereIn('id', $id)->update(['is_del' => 1]);
        } else {
            $row = $table->where('id', $id)->update(['is_del' => 1]);
        }
        return $row ? self::successResult("成功") : self::errorResult("失败");
   }
  
   public function is_display()
   {
       $id = request()->param('id');
       $is_display = request()->param('is_display');
       if (empty($id)) $this->error("请选择要修改的数据");
       $table = new \app\common\model\AgentGoodsSku();
       $row = $table->where('id', $id)->update(['is_display' => $is_display]);
       return $row ? self::successResult() : self::errorResult('操作失败!请刷新后重试！');
   }
   public function is_recommend()
   {
       $id = request()->param('id');
       $is_recommend = request()->param('is_recommend');
       if (empty($id)) $this->error("请选择要修改的数据");
       $table = new \app\common\model\AgentGoodsSku();
       $row = $table->where('id', $id)->update(['is_recommend' => $is_recommend]);
       return $row ? self::successResult() : self::errorResult('操作失败!请刷新后重试！');
   }
   public function export(){
            $search = request()->param();
            $time = date('YmdHis',time());
            $expFileType = "xlsx";
            $expFileName = '导出';
            $expFileName .= "_".$time.".".$expFileType;
            //设置保存路径
            $basePath = request()->env('ROOT_PATH').'public/uploads';
            $baseUrl  = DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, ['excel',date('Y-m-d',time())]). DIRECTORY_SEPARATOR;
            $path = $basePath.$baseUrl;
            //路径不存在则创建路径
            if(!is_dir($path)){
                mkdir($path, 0777, true);
            }
            $path = $path.$expFileName; 
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            $defaultStyle = $spreadsheet->getDefaultStyle(); 
            $align = $defaultStyle->getAlignment();
            $align->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
            $sheet->getColumnDimension('A')->setWidth(20);
            $sheet->getColumnDimension('B')->setWidth(50);
            $sheet->getColumnDimension('C')->setWidth(28);
       
            
            $sheet->getStyle('A1')->getFont()->setSize(12)->setBold(true);
            $sheet->getStyle('B1')->getFont()->setSize(12)->setBold(true);
            $sheet->getStyle('C1')->getFont()->setSize(12)->setBold(true);
            $sheet->setCellValue('A1', '商品id(别改)');
            $sheet->setCellValue('B1', '商品名称(别改)');
            $sheet->setCellValue('C1', '商品价格');

            $table = (new \app\common\model\AgentGoodsSku())
            ->alias('agent_goods_sku')
            ->join("{$this->tdb}goods goods","goods.id = agent_goods_sku.goods_id")
            ->join("{$this->tdb}goods_sku goods_sku","goods_sku.id = agent_goods_sku.goods_sku_id")
            ->field([
                'agent_goods_sku.id',
                'agent_goods_sku.stock',
                'goods.cate_id','goods.title','goods_sku.sku_title',
                'agent_goods_sku.sort','agent_goods_sku.is_display',
                'agent_goods_sku.is_recommend',
                'agent_goods_sku.money',
                'agent_goods_sku.money_primary',
                'agent_goods_sku.money_cost'
                ])
            ->where(['agent_goods_sku.is_del' => 0,'agent_goods_sku.agent_id' => $this->userInfo['id'],'goods.is_del' => 0]);
            isset($search['goods_title']) && $search['goods_title'] != "" ? $table->where("title like '%{$search['goods_title']}%'") : '';
            !empty($search['id']) && is_array($search['id']) ? $table->whereIn('agent_goods_sku.id', implode(",", $search['id'])) : '';
            $data = $table->select()->toArray();
        
            if(empty($data)){
                return json(['code' => 1, 'msg' => '当前数据为空', 'data' => []]);  
            }
            $row = 2;
            foreach ($data as $key => $value) {
                $sheet->setCellValue('A'.$row, $value['id']."\t");
                $sheet->setCellValue('B'.$row, $value['title'].'-'.$value['sku_title']."\t");
                $sheet->setCellValue('C'.$row, $value['money']."\t");
                $sheet->getRowDimension($row)->setRowHeight(100);
                $row++;
            }
            $filename = time().'.xlsx';
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="'.$filename.'"');
            header('Cache-Control: max-age=0');
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save($path);
            return json(['code' => 0, 'state' => 1, 'data' => "http://".request()->host().'/uploads/'.$baseUrl.$expFileName]);  
   }
   public function import(){
        $execl_data = (new \app\common\controller\Upload())->execl();
        if($execl_data['state'] == 0){
            return json(['code' => 0, 'state' => 1,'data' => [],'msg' => $execl_data['msg']]);  
        }
        $excelFile = ".".$execl_data['data']['url'];
        $spreadsheet = IOFactory::load($excelFile);
        $sheetSelected = 0;
        $spreadsheet->setActiveSheetIndex($sheetSelected);
        $rowCount = $spreadsheet->getActiveSheet()->getHighestRow();
        for ($i = 2; $i <= $rowCount; $i++) {
            $id = $spreadsheet->getActiveSheet()->getCell("A" . $i)->getValue();
            $money = $spreadsheet->getActiveSheet()->getCell("C" . $i)->getValue();
            (new \app\common\model\AgentGoodsSku())->where(['id' => $id])->update(['money' => $money]);
        }
        return json(['code' => 1, 'state' => 1,'data' => [],'msg' => '成功']);  
   }
   public function fiex(){
        $id = request()->param('id');
        $key = request()->param('key');
        $value = request()->param('value');
        ((new \app\common\model\AgentGoodsSku()))->where(['id' => $id])->update([$key => $value]);
        return json(['code' => 1, 'state' => 1,'data' => [],'msg' => '成功']);  
   }
}
